package com.hefan.live.service;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.CollectionUtils;
import com.hefan.common.util.PayPropertiesUtils;
import com.hefan.live.bean.LiveLog;
import com.hefan.live.bean.LiveRoom;
import com.hefan.live.bean.LiveRoomVo;
import com.hefan.live.bean.LivingRoomInfoVo;
import com.hefan.live.dao.LiveLogDao;
import com.hefan.live.dao.LiveRoomDao;
import com.hefan.live.itf.LiveRoomService;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.live.itf.RoomEnterExitOptService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by nigle on 2016/9/28.
 */
@Component("liveRoomService")
public class LiveRoomServiceImpl implements LiveRoomService {

    private Logger logger = LoggerFactory.getLogger(LiveRoomServiceImpl.class);

    @Resource
    LiveRoomDao liveRoomDao;
    @Resource
    LiveLogDao liveLogDao;
    @Resource
    WebUserService webUserService;
    @Resource
    LivingRedisOptService livingRedisOptService;
    @Resource
    RoomEnterExitOptService roomEnterExitOptService;
    @Resource
    JedisService jedisService;

    @Override
    @Transactional(readOnly = true)
    public LiveRoom getLiveRoom(String userId) {
        return liveRoomDao.getLiveRoomByUserId(userId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateLiveRoomForRebalance(LiveRoom liveRoom) {
        return liveRoomDao.updateLiveRoomForRebalance(liveRoom);
    }

    @Override
    public List<LivingRoomInfoVo> recommendLive() {
        List<LivingRoomInfoVo> map = roomEnterExitOptService.getAllLivingRoomInfoList();
        List<LivingRoomInfoVo> list = new ArrayList<LivingRoomInfoVo>();
        for (LivingRoomInfoVo live : map) {
            if (list.size() >= 6) {
                break;
            }

            long watchNum = livingRedisOptService.getLivingUserCount_SortedSet(live.getUserId());
            try {
                String addNUm = livingRedisOptService.getAddNumForRoom(live.getUserId());
                if ( null != addNUm && Long.valueOf(addNUm) >= 0) {
                    watchNum += Long.valueOf(addNUm);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            live.setPeopleCount(watchNum);
            live.setStatus(1);
            list.add(live);

        }
        return list;
    }

    /**
     * 查询正在直播的liveRoom集合
     *
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<LiveRoom> getLivingRoomList() {
        return liveRoomDao.getLivingRoomList();
    }

    @Override
    @Transactional(readOnly = true)
    public LivingRoomInfoVo findLiveRoomById(String roomId) {
        LivingRoomInfoVo livingRoomInfoVo = new LivingRoomInfoVo();
        LiveRoom liveRoom = liveRoomDao.getLiveRoomByChatRoomId(Integer.valueOf(roomId));
        livingRoomInfoVo = roomEnterExitOptService.getLivingRoomInfoByAuthId(liveRoom.getUserId());
        WebUser webUser = webUserService.findUserInfoFromCache(liveRoom.getUserId());
        if (webUser == null || webUser.getState() != 0 || webUser.getIsDel() == 1 || webUser.getSuperiorState() != 0) {
            return new LivingRoomInfoVo();
        }
        if (livingRoomInfoVo == null) {
            livingRoomInfoVo = new LivingRoomInfoVo();
            livingRoomInfoVo.setHeadImg(webUser.getHeadImg() == null ? "" : webUser.getHeadImg());
            livingRoomInfoVo.setName(webUser.getNickName() == null ? "" : webUser.getNickName());
            livingRoomInfoVo.setLiveImg(liveRoom.getLiveImg() == null ? "" : liveRoom.getLiveImg());
            livingRoomInfoVo.setChatRoomId(liveRoom.getChatRoomId() == 0 ? 0 : liveRoom.getChatRoomId());
            livingRoomInfoVo.setLocation(webUser.getGpsLocation() == null ? "" : webUser.getGpsLocation());
            livingRoomInfoVo.setType(webUser.getUserType() == 0 ? 0 : webUser.getUserType());
            livingRoomInfoVo.setPersonSign(liveRoom.getLiveName() == null ? "" : liveRoom.getLiveName());
            livingRoomInfoVo.setUserId(liveRoom.getUserId());
            livingRoomInfoVo.setStatus(0);
        } else {
            livingRoomInfoVo.setPeopleCount(livingRedisOptService.getLivingUserCount_SortedSet(liveRoom.getUserId()));
            livingRoomInfoVo.setStatus(1);
        }

        livingRoomInfoVo.setLiveUuid(liveRoom.getLiveUuid());
        livingRoomInfoVo.setUserId(liveRoom.getUserId());
        return livingRoomInfoVo;
    }

    @Override
    @Transactional(readOnly = true)
    public LiveRoom getLiveRoomByChatRoomId(int chatRoomId) {
        return liveRoomDao.getLiveRoomByChatRoomId(chatRoomId);
    }

    private final String START = PayPropertiesUtils.getString("monitor.one");
    private final String END = ".jpg";

    @Override
    public List<LiveRoomVo> getLivingList(Page po) {
        //在播列表
        List<LiveRoomVo> list = liveRoomDao.getLivingListByPage(po);
        //在播redis数据
        List<LivingRoomInfoVo> redisList = roomEnterExitOptService.getALLMonitorLivingRoomInfoList();

        List<LiveRoomVo> listOther = new ArrayList();

        for (LiveRoomVo liveRoom : list) {
            if (!CollectionUtils.isEmptyList(redisList)) {
                for (LivingRoomInfoVo vo : redisList) {
                    if (vo.getUserId().equals(liveRoom.getUserId())) {
                        liveRoom.setNickName(vo.getName());
                        liveRoom.setChatRoomId(vo.getChatRoomId());
                        liveRoom.setLiveUuid(vo.getLiveUuid());
                        liveRoom.setUserType(vo.getType());
                        liveRoom.setPullUrl(vo.getPullUrls());
                        liveRoom.setIsVipLive(vo.getIsVipLive());
                        liveRoom.setIsShow(vo.getIsShow());
                        liveRoom.setRotate(vo.getRotate());
                        liveRoom.setDoubleSrc(vo.getDoubleSrc());
                        logger.info("monitorLiveList" + liveRoom.getUserId() + "[" + liveRoom.getIsVipLive() + "]" + "[" + vo.getIsVipLive() + "]");
                        liveRoom.setLivingPic(START + liveRoom.getLiveUuid() + END);
                        liveRoom.setStartTime(new Date(vo.getStartLiveTime()));
                        liveRoom.setPeopleCount(vo.getPeopleCount());
                        listOther.add(liveRoom);
                    }
                }
            }

        }
        return listOther;
    }

    @Override
    public LiveRoomVo findLiveRoomByIdFormonitor(String userId, String uuid) {
        LiveRoomVo liveRoomVo = new LiveRoomVo();
        Date endDate = new Date();
        Date startDate = new Date();
        LivingRoomInfoVo redisVo = roomEnterExitOptService.getLivingRoomInfoByAuthId(userId);
        if(redisVo != null && StringUtils.isNotBlank(redisVo.getLiveUuid())){
            liveRoomVo.setUserId(redisVo.getUserId());
            liveRoomVo.setNickName(redisVo.getName());
            liveRoomVo.setChatRoomId(redisVo.getChatRoomId());
            liveRoomVo.setLiveUuid(redisVo.getLiveUuid());
            liveRoomVo.setUserType(redisVo.getType());
            liveRoomVo.setPullUrl(redisVo.getPullUrls());
            liveRoomVo.setIsVipLive(redisVo.getIsVipLive());
            liveRoomVo.setIsShow(redisVo.getIsShow());
            liveRoomVo.setRotate(redisVo.getRotate());
            liveRoomVo.setDoubleSrc(redisVo.getDoubleSrc());
            liveRoomVo.setLivingPic(START + redisVo.getLiveUuid() + END);
            startDate = new Date(redisVo.getStartLiveTime());
            liveRoomVo.setStartTime(startDate);
            liveRoomVo.setPeopleCount(redisVo.getPeopleCount());
        }else{
            //缓存未获取到数据，走库.
            WebUser user = webUserService.getWebUserInfoByIsDel(userId,2);
            logger.info("findLiveRoomByIdFormonitor-读库-用户:" + JSON.toJSONString(user));
            LiveLog liveLog = liveLogDao.getLiveLogByUuid(uuid);
            logger.info("findLiveRoomByIdFormonitor-读库-直播日志:" + JSON.toJSONString(liveLog));
            if(liveLog == null || StringUtils.isBlank(liveLog.getLiveUuid())){
                return null;
            }
            liveRoomVo.setUserId(liveLog.getUserId());
            liveRoomVo.setNickName(user==null?"":user.getNickName());
            liveRoomVo.setChatRoomId(liveLog.getChatRoomId());
            liveRoomVo.setLiveUuid(liveLog.getLiveUuid());
            liveRoomVo.setUserType(user == null ? 0:user.getUserType());
            liveRoomVo.setPullUrl(liveLog.getPullUrl());
            liveRoomVo.setIsVipLive(liveLog.getIsVipLive());
            liveRoomVo.setIsShow(liveLog.getIsShow());
            liveRoomVo.setRotate(0);
            liveRoomVo.setDoubleSrc(0);
            liveRoomVo.setLivingPic(START + liveLog.getLiveUuid() + END);
            startDate= liveLog.getStartTime();
            endDate = liveLog.getEndTime() == null?new Date():liveLog.getEndTime();
            liveRoomVo.setStartTime(startDate);
            liveRoomVo.setPeopleCount(liveLog.getWatchNum());
        }

        int interval = (int) ((endDate.getTime() - startDate.getTime()) / 1000) / 5;
        String msg = START + uuid + "/" + interval + END;
        while (!this.checkImgHas(msg)) {
            if (interval <= 0) {
                break;
            }
            interval--;
            msg = START + uuid + "/" + interval + END;
        }

        int change = 0;
        if (interval - 12 < 0) {
            change = interval;
        } else {
            change = 12;
        }

        List picList = new ArrayList();
        for (int i = 0; i < change; i++) {
            String img = START + uuid + "/" + (interval - i) + END;
            picList.add(img);
        }

        liveRoomVo.setPicList(picList);
        return liveRoomVo;
    }

    @Override
    public ResultBean listHostIndex() {
        ResultBean resultBean = new ResultBean();
        try {

            resultBean.setCode(ResultCode.SUCCESS.get_code());

            List list = liveRoomDao.listHostIndex();
            resultBean.setData(list);
            ByteArrayInputStream buf = new ByteArrayInputStream(JSON.toJSONString(resultBean).getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultBean;
    }

    @Override
    public List getshareWordsForBefore() {
        return liveRoomDao.getshareWordsForBefore();
    }

    @Override
    public List getshareWordsForAfter() {
        return liveRoomDao.getshareWordsForAfter();
    }

    /**
     * 判断图片是否存在
     *
     * @param imgUrl
     * @return
     * @throws @date: 2016年11月11日 上午10:44:45
     * @Title: checkImgHas
     * @Description:
     * @return: boolean
     * @author: LiTeng
     */
    private boolean checkImgHas(String imgUrl) {
        try {
            URL url = new URL(imgUrl);
            // 返回一个 URLConnection 对象，它表示到 URL 所引用的远程对象的连接。
            URLConnection uc = url.openConnection();
            // 打开的连接读取的输入流。
            InputStream in = uc.getInputStream();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
